<!-- 生产统计 -->
<template>
  <div class="container-statistic" v-loading="loading">
    <!-- 查询 -->
    <div class="search">
      <el-form :inline="true" :model="formInline">
        <el-form-item>
          <el-radio-group v-model="tabPosition" @input="timeChange">
            <el-radio-button v-for="(row, index) in dateTab" :key="index" :label="row">{{ row }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$i18n.t('mesProduceStatistic.customTime')" label-width="110px">
          <el-date-picker v-model="value1" type="daterange" range-separator="~" :start-placeholder="$i18n.t('mesProduceStatistic.beginDate')"
            :end-placeholder="$i18n.t('mesProduceStatistic.endDate')" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$i18n.t('mesProduceStatistic.workshop')" label-width="70px">
          <el-select v-model="formInline.workshopCode" :placeholder="$i18n.t('mesProduceStatistic.pleaseSelectWorkshop')" @change="workshopSelect" filterable>
            <el-option v-for="item in workshopList" :key="item.modelingCode" :label="item.modelingName"
              :value="item.modelingCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$i18n.t('mesProduceStatistic.line')" label-width="70px">
          <el-select v-model="formInline.lineCode" :placeholder="$i18n.t('mesProduceStatistic.selectLine')" filterable>
            <el-option v-for="item in lineList" :key="item.modelingCode" :label="item.modelingName"
              :value="item.modelingCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSubmit" icon="el-icon-search">{{ $i18n.t("mesProduceStatistic.search") }}</el-button>
          <el-button @click="resetSubmit" icon="el-icon-refresh">{{ $i18n.t("common.reset") }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 生产分析  -->
    <product-analysis :analysisData="analysisData" />
    <div class="flex-wrap">
      <!-- 开完工产品统计 -->
      <product-statist ref="statist" :setType.sync="type" />
      <!-- 车间生产统计 -->
      <workshop-product :workshopStatistics="workshopStatistics" />
      <!-- 异常分析 -->
      <abnormal-analysis ref="abnormal" />
      <!-- 物料需求分析 -->
      <require-analysis ref="require" :requireData="requireData" />
    </div>
  </div>
</template>

<script>
import moment from "moment";
import {
  getLineCodeList, //查询线体
  getLineCodeListNew, //查询车间
} from "@/api/order/mesProdOrder";
import * as api from "@/api/report/mesProduceStatistic";
import productAnalysis from "./components/product-analysis.vue";
import productStatist from "./components/product-statist.vue";
import workshopProduct from "./components/workshop-product.vue";
import abnormalAnalysis from "./components/abnormal-analysis.vue";
import requireAnalysis from "./components/require-analysis.vue";
export default {
  name: "mesProduceStatistic",
  components: { productAnalysis, productStatist, workshopProduct, abnormalAnalysis, requireAnalysis },
  data() {
    return {
      tabPosition: $i18n.t('common.today'),
      dateTab: [$i18n.t('common.yesterday'), $i18n.t('common.today'), $i18n.t('common.thisWeek'), $i18n.t('mesProduceStatistic.thisMonth')],
      value1: [moment().format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")],
      formInline: {
        workshopCode: "",
        lineCode: "",
        beginDate: "",
        endDate: "",
      },
      type: 1,
      lineList: [], // 线体
      workshopList: [], //车间
      analysisData: {},
      workshopStatistics: [],
      requireData: [],
      loading: false
    };
  },
  created() {
    this.formInline.beginDate = this.value1[0];
    this.formInline.endDate = this.value1[1];
    this.init()
  },
  methods: {
    searchSubmit() {
      this.formInline.beginDate = this.value1[0];
      this.formInline.endDate = this.value1[1];
      this.init()
    },
    resetSubmit() {
      this.formInline = {
        workshopCode: "",
        lineCode: "",
      };
      this.value1 = [
        moment().format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD"),
      ];
      this.lineList = [];
      this.searchSubmit()
    },
    init() {
      this.loading = true
      try {
        this.getWorkshopData()
        this.getProductAnalysis()
        this.getFinishStatistics()
        this.getWorkshopStatistics()
        this.getAnomalyAnalysis()
        this.getMaterialRequirement()
      } finally {
        this.loading = false
      }
    },
    async getProductAnalysis() {
      await Promise.all([
        api.productAnalysis(this.formInline),
        api.materialDistribution(this.formInline)
      ]).then(res => {
        this.analysisData = { ...res[0].data.result[0], ...res[1].data.result[0] }
      })
    },
    getFinishStatistics() {
      api.finishStatistics({ ...this.formInline, type: this.type }).then((res) => {
        let data = res.data.result;
        if (data.length) {
          this.$nextTick(() => {
            this.$refs.statist.noData = false
            this.$refs.statist.init(data)
          })
        } else {
          this.$refs.statist.noData = true
        }
      });
    },
    getWorkshopStatistics() {
      api.workshopStatistics(this.formInline).then((res) => {
        this.$nextTick(() => {
          this.workshopStatistics = res.data.result;
        })
      });
    },
    getAnomalyAnalysis() {
      api.anomalyAnalysis(this.formInline).then((res) => {
        let data = res.data.result;
        if (data.length) {
          this.$nextTick(() => {
            this.$refs.abnormal.noData = false
            this.$refs.abnormal.init(data)
          })
        } else {
          this.$refs.abnormal.noData = true
        }
      });
    },

    getMaterialRequirement() {
      api.materialRequirement(this.formInline).then((res) => {
        this.requireData = res.data.result;
      });
    },
    // 获取车间
    async getWorkshopData() {
      try {
        const list = await getLineCodeListNew({
          modelingCode: this.$store.getters.factoryCode,
          level: 4,
          modelingType: "0",
        });
        this.workshopList = list.data.result || [];
      } catch (error) {
        console.error(error);
      }
    },
    async workshopSelect(val) {
      this.formInline.lineCode = "";
      const params = {
        level: 5,
        modelingCode: val,
      };
      const list = await getLineCodeList(params);
      this.lineList = list.data.result || [];
    },
    timeChange(val) {
      if (val == $i18n.t('common.yesterday')) {
        let timer = moment().subtract(1, "days").format("YYYY-MM-DD");
        this.value1 = [timer, timer];
      } else if (val == $i18n.t('common.today')) {
        this.value1 = [
          moment().format("YYYY-MM-DD"),
          moment().format("YYYY-MM-DD"),
        ];
      } else if (val == $i18n.t('common.thisWeek')) {
        let startWeek = moment().startOf("isoWeek").format("YYYY-MM-DD");
        let endWeek = moment().endOf("isoWeek").format("YYYY-MM-DD");
        this.value1 = [startWeek, endWeek]
      } else {
        let startMonth = moment().startOf("month").format("YYYY-MM-DD");
        let endMonth = moment().endOf("month").format("YYYY-MM-DD");
        this.value1 = [startMonth, endMonth]
      }
    },
  },
};
</script>
<style scoped lang='scss' >
.container-statistic {
  background: #f5f7fa;
  padding: 10px;

  .flex-wrap {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
}
</style>